package org.ojudge.ojudgecodesandbox.controller;

import lombok.extern.slf4j.Slf4j;
import org.ojudge.ojudgecodesandbox.modal.ExecuteCodeRequest;
import org.ojudge.ojudgecodesandbox.modal.ExecuteCodeResponse;
import org.ojudge.ojudgecodesandbox.sandbox.impl.JavaNativeCodeSandbox;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
@Slf4j
public class MainController {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";//TODO,先写一个假值

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    @GetMapping("/health")
    public String healthCheck() {
        return "OK";
    }

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response) {
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return ExecuteCodeResponse.builder()
                    .message("没有权限,禁止访问")
                    .status(403)
                    .build();
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求为空");
        }
        log.info("executeCodeRequest{}", executeCodeRequest);
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        log.info("executeCodeResponse{}", executeCodeResponse);
        return executeCodeResponse;
    }
}
